package top.revery.admin.controller_admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import top.revery.admin.util.FeignServiceMapping;
import top.revery.api.config.HttpResponResult;
import top.revery.api.config.ResultType;
import top.revery.api.entity.other.BaseCategory;
import top.revery.api.util.reveryTool;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * <h1> --- 分类管理 --- </h1>
 * Created by  revery.top jun
 * Date  2019-12-09 17:22
 */
@RestController
@RequestMapping("/admin/category")
public class CategoryController {

    @RequestMapping("/save")
    Object save(HttpServletRequest request) throws Exception {
        BaseCategory baseCategory = new BaseCategory();
        reveryTool.implantData(baseCategory,request.getParameterMap());

        if(baseCategory.getId()!=null && baseCategory.getId().intValue()==baseCategory.getParentID().intValue()){
            throw new Exception("不能设置所属栏目为本身类目！");
        }

        FeignServiceMapping.categoryDataSource.save(baseCategory);

        HttpResponResult httpResponResult = new HttpResponResult(ResultType.SUCCESS);
        httpResponResult.put("id",baseCategory.getId());

        return httpResponResult;
    }

    @RequestMapping("/delete")
    Object delete(@RequestParam(defaultValue = "0") Long id) {
        //如果有子分类，先移除子分类
        JSONArray array = (JSONArray) foreachCategoryList(Integer.valueOf(String.valueOf(id)));
        if(array!=null){
            foreachDel(array);
        }

        FeignServiceMapping.categoryDataSource.del(id);

        HttpResponResult httpResponResult = new HttpResponResult(ResultType.SUCCESS);
        return httpResponResult;
    }

    @RequestMapping("/getAll")
    Object getAll(@RequestParam(defaultValue = "0") int parentID){

        HttpResponResult httpResponResult = null;
        try{

            BaseCategory baseCategory = new BaseCategory();
            baseCategory.setName("浪荡小野狗2");
            baseCategory.setParentID(0);
            baseCategory = FeignServiceMapping.categoryDataSource.save(baseCategory);
            System.out.println(baseCategory);

            JSONArray array = (JSONArray) foreachCategoryList(parentID);

            httpResponResult = new HttpResponResult(ResultType.SUCCESS);
            httpResponResult.put("List",array);
        }catch (Exception e){
            e.printStackTrace();
            httpResponResult = new HttpResponResult(ResultType.ERROR_SERVICE);
            httpResponResult.exception = e;
        }

        return httpResponResult;
    }

    @RequestMapping("/init")
    Object initCategory() throws Exception {
        File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+"config/category.json");
        JSONObject json = JSON.parseObject(FileUtils.readFileToString(file));

        JSONArray tagArray = json.getJSONObject("data").getJSONArray("style_tag");
        for(int i=0; i<tagArray.size(); i++){
            JSONObject tag = tagArray.getJSONObject(i);

            BaseCategory baseCategory = new BaseCategory();
            JSONObject firstObj = tag;
            for(String key:firstObj.keySet()){
                baseCategory.setName(String.valueOf(firstObj.get(key)));
                baseCategory.setParentID(108);

                baseCategory  = FeignServiceMapping.categoryDataSource.save(baseCategory);
            }
        }

        HttpResponResult httpResponResult = new HttpResponResult(ResultType.SUCCESS);

        return httpResponResult;
    }


    /*----------------------辅助方法--------------------------*/
    void foreachDel(JSONArray array){
        for(int i=0; i<array.size(); i++){
            JSONObject json = array.getJSONObject(i);

            JSONArray childs = json.getJSONArray("childs");
            if(childs.size()>0){
                foreachDel(childs);
            }

            FeignServiceMapping.categoryDataSource.del(json.getLong("id"));
        }
    }

    /*
    * 循环获取所有子分类
    * */
    Object foreachCategoryList(int parentID) {
        List<BaseCategory> baseCategories = FeignServiceMapping.categoryDataSource.getList(parentID);
        JSONArray array = new JSONArray();

        if(baseCategories!=null){
            for(BaseCategory baseCategory : baseCategories){
                JSONObject obj = (JSONObject) JSON.toJSON(baseCategory);

                obj.put("addTime", reveryTool.timeToString(baseCategory.getAddTime().getTime()));
                obj.put("childs",foreachCategoryList(Integer.valueOf(String.valueOf(baseCategory.getId()))));

                array.add(obj);
            }
        }

        return array;
    }

}
